﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Kevin.Service.Client.Restful;
using Kevin.Shop.Business.SalesManagement.Components.Order;
using Kevin.Shop.Business.Service.Entity.Helper;
using RiderShop.Mobile.Common.Component;
using Kevin.Shop.Business.Core.Components.Responser;
using Kevin.Shop.Business.Service.Entity.SalesManagement.Order;
using System.Configuration;
using Kevin.Comm.Utility;
using System.IO;

namespace RiderShop.Mobile.Modle.Purchase
{
    public class PaymentModel
    {
        public OrderBasicInfo OrderBasicInfo { get; set; }

        public string PaymentResult { get; set; }

        public OrderBasicInfo GetOrderBasicInfoByOrderId(string orderId)
        {
            ////取Order信息
            var client = new ResourceClient<OrderBasicInfo>();
            var order = RestfulHelper.QueryWithSingle<OrderBasicInfo>(SiteUrl.FormatUrl("SalesManagement_GetOrderDetailInfo", orderId));
            return order;
        }

        public ServiceResponser CreateOrderPaymentInfo(string order_no, string trade_no, decimal orderPayAmount, string buyer_email, int paymentPlatformType = 1)
        {
            var info = new OrderPaymentInfo
            {
                OrderNumber = order_no,
                TradeNumber = trade_no,
                TransferAmount = orderPayAmount,
                InDate = DateTime.Now,
                BuyerPaymentID = buyer_email,
                PaymentPlatformType = paymentPlatformType,
                InUser = 100
            };
            var response = RestfulHelper.Update(SiteUrl.FormatUrl("SalesManagement_CreateOrderPaymentInfo"), info);
            return response;
        }


        /// <summary>
        /// 获取订单支付折扣信息
        /// </summary>
        /// <param name="discountString"></param>
        /// <returns></returns>
        public List<KeyValuePair<decimal, decimal>> GetPaymentDiscountList(string discountString)
        {
            List<KeyValuePair<decimal, decimal>> discountList = new List<KeyValuePair<decimal, decimal>>();

            if (!string.IsNullOrEmpty(discountString))
            {
                foreach (var dis in discountString.Split(','))
                {
                    var par = dis.Split('-');
                    discountList.Add(new KeyValuePair<decimal, decimal>(decimal.Parse(par[0]), decimal.Parse(par[1])));
                }
                return discountList;
            }

            return null;
        }

        public decimal GetOrderPaymentDiscount(string discountString)
        {
            if (string.IsNullOrEmpty(discountString) || OrderBasicInfo == null || OrderBasicInfo.OrderPayAmount <= 0)
            {
                return 0M;
            }

            if (discountString.Contains("-"))
            {
                var discountList = GetPaymentDiscountList(discountString);
                if (discountList != null)
                {
                    discountList = discountList.OrderByDescending(d => d.Key).ToList();
                    foreach (var dis in discountList)
                    {
                        if (OrderBasicInfo.OrderPayAmount >= dis.Key)
                        {
                            return dis.Value;
                        }
                    }
                }
            }
            else if (discountString.Contains("%"))
            {
                decimal rate = 0M;
                if (decimal.TryParse(discountString.Replace("%", ""), out rate) && rate < 100)
                {
                    decimal discount = OrderBasicInfo.OrderPayAmount * rate / 100;
                    //四舍五入
                    decimal newDiscount = decimal.Round(discount, 2, MidpointRounding.AwayFromZero);

                    return newDiscount;
                }
            }

            return 0M;
        }

        public decimal GetOrderPaymentDiscount(PaymentPlatformType paymentPlatformType)
        {
            if (OrderBasicInfo != null)
            {
                if (OrderBasicInfo.ProductList.Any(p => p.ProductId.StartsWith("GC")))
                {
                    return 0M;
                }
                switch (paymentPlatformType)
                {
                    case PaymentPlatformType.XianXiangCard:
                        return GetOrderPaymentDiscount(ConfigurationManager.AppSettings["YinxinPayDiscount"]);
                    case PaymentPlatformType.XianXiangLianMingCard:
                        return GetOrderPaymentDiscount(ConfigurationManager.AppSettings["LianMingCardDiscount"]);
                }
            }

            return 0M;
        }

        public PaymentPlatformType CheckYinXinCardType(string cardNumber)
        {
            if (!string.IsNullOrWhiteSpace(cardNumber))
            {
                cardNumber = cardNumber.Trim();
                if (cardNumber.StartsWith(ConfigurationManager.AppSettings["XianxiangCardPrefix"]))
                {
                    if (IsLianMingCard(cardNumber))
                    {
                        return PaymentPlatformType.XianXiangLianMingCard;
                    }
                    else
                    {
                        return PaymentPlatformType.XianXiangCard;
                    }
                }
                else
                {
                    return PaymentPlatformType.ShangTongCard;
                }
            }
            return PaymentPlatformType.NaN;
        }

        public bool IsLianMingCard(string cardNumber)
        {
            string CacheKeyBMWCard = "CacheKeyBMWCard";
            var cardList = KevinCache.Exists(CacheKeyBMWCard) ? KevinCache.Get(CacheKeyBMWCard).ToString() : string.Empty;

            if (string.IsNullOrEmpty(cardList))
            {
                string fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Configuration\LianMingCardNumber.txt");
                if (File.Exists(fileName))
                {
                    cardList = File.ReadAllText(fileName);
                    KevinCache.Insert(CacheKeyBMWCard, cardList, 60 * 60 * 24 * 7);
                }
                else
                {
                    return false;
                }
            }
            if (cardList.Contains(cardNumber))
            {
                return true;
            }
            return false;
        }


    }

    public enum PaymentPlatformType
    {
        NaN = 0,
        Alipay = 1,
        WeixinPay = 3,
        XianXiangCard = 4,
        ShangTongCard = 5,
        XianXiangLianMingCard = 6
    }
}
